package com.atguigu1.util;



import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    /**
     *
     * @return
     * @throws Exception
     * 获取数据库连接操作
     */
    public static Connection getConnection() throws Exception {
        //1.读取配置文件
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");

        Properties pros = new Properties();

        pros.load(is);

        //2.获取信息
        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String driverClass = pros.getProperty("driverClass");

        //3.加载驱动
        Class.forName(driverClass);

        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }


    /**
     *
     * @param conn
     * @param ps
     * 关闭资源
     */
    public static void closeResource(Connection conn, PreparedStatement ps){
        try {
            if(conn != null)
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        try {
            if(ps != null)
            ps.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void closeResource(Connection conn, PreparedStatement ps, ResultSet rs){
        try {
            if(conn != null)
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if(ps != null)
            ps.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if(rs != null)
            rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
